import ApiV1WxContactSave_post from "@/api/ApiV1WxContactSave_post";
import { PhoneInput } from "@/component/PhoneInput";
import { Toast } from "@/hooks/Providers";
import { IContactItem } from "@/mgr";
import { QuestionCircleFilled } from "@ant-design/icons";
import { Flex, Form, FormInstance, Input, InputProps, Modal, ModalProps, Tooltip, Typography } from "antd";
import { useEffect, useRef, useState } from "react";

type Values = Partial<ApiV1WxContactSave_post.BodyParams>;
export interface IContactEditViewProps {
  data?: IContactItem;
  on_form_change?(form: null | FormInstance<Values>): void;
  on_submitting?(submitting: boolean): void;
  on_success?(edited: IContactItem): void;
}

export function ContactEditView(props: IContactEditViewProps) {
  const { data, on_form_change, on_submitting, on_success } = props;
  const [form] = Form.useForm<Values>()
  const [toast] = Toast.use()
  useEffect(() => {
    on_form_change?.(form);
    return () => on_form_change?.(null)
  }, [])
  useEffect(() => {
    if (!data) form.resetFields()
    else form.setFieldsValue(data)
  }, [data])

  const on_finish = (values: Values) => {
    if (!data) return;
    on_submitting?.(true);
    const edited: IContactItem = { ...data, ...values, phone: values.phone?.trim() }
    ApiV1WxContactSave_post.call(edited).then(r => {
      toast.success('修改成功')
      on_success?.(edited)
    }).catch(e => {
      toast.error(e)
    }).finally(() => {
      on_submitting?.(false);
    })
  }

  return (
    <Form form={form} onFinish={on_finish}>
      <Form.Item label="手机号" name='phone'>
        <PhoneInput />
      </Form.Item>
    </Form>
  )
}

export interface IContactEditModalProps extends ModalProps, IContactEditViewProps { }
export function ContactEditModal(props: IContactEditModalProps) {
  const { data, on_form_change, on_submitting, on_success, afterClose, open, ..._p } = props;
  const ref_form = useRef<FormInstance<Values> | null>(null)
  const [pending, set_pending] = useState(false)


  return (
    <Modal
      title={<Flex align='center' gap={5}>
        设置联系人信息
        <Tooltip title="仅支持修改外部数据，无法更改微信内部数据">
          <Typography.Text type='secondary'>
            <QuestionCircleFilled />
          </Typography.Text>
        </Tooltip>
      </Flex>}
      {..._p}
      open={open}
      onOk={() => ref_form.current?.submit()}
      okButtonProps={{ disabled: pending }}
      afterClose={() => {
        afterClose?.()
        ref_form.current?.resetFields()
      }}
      cancelButtonProps={{ disabled: pending }}>
      <ContactEditView
        data={data}
        on_form_change={f => {
          ref_form.current = f
          on_form_change?.(f);
        }}
        on_submitting={v => {
          set_pending(v);
          on_submitting?.(v)
        }}
        on_success={on_success} />
    </Modal>
  )
}

